package com.weng.apistarter.config;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.Ordered;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.Arrays;

/**
 * 跨域请求处理
 */
@Configuration
public class CrosConfig {
	
	private CorsConfiguration buildConfig() {
        CorsConfiguration corsConfiguration = new CorsConfiguration();
        corsConfiguration.addAllowedOrigin("*"); // 1
        corsConfiguration.addAllowedHeader("*"); // 2
        corsConfiguration.addAllowedMethod("*"); // 3
        return corsConfiguration;
    }

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", buildConfig()); // 4
        return new CorsFilter(source);
    }

//	@Bean
//	public FilterRegistrationBean filterRegistrationBean() {
//			final UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
//			final CorsConfiguration config = new CorsConfiguration();
//
//			config.setAllowCredentials(true);
//			config.setAllowedOrigins(Arrays.asList("*"));
//			config.setAllowedHeaders(Arrays.asList("*"));
//			config.setAllowedMethods(Arrays.asList("*"));
//			config.setMaxAge(300L);
//
//			source.registerCorsConfiguration("/**", config);
//			CorsFilter corsFilter = new CorsFilter(source);
//			FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(corsFilter);
//			// 设置为 Ordered.HIGHEST_PRECEDENCE
//			filterRegistrationBean.setOrder(Ordered.HIGHEST_PRECEDENCE);
//			return filterRegistrationBean;
//	}

}
